﻿using Newtonsoft.Json;

namespace Service.Framework.Utils
{
    /// <summary>
    /// 把前端传过来的空字符串转换成默认数字
    /// </summary>
    public class JsonConverterByte : JsonConverter
    {
        /// <summary>
        /// 是否可以转换
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        /// <summary>
        /// 读json
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if ((reader.ValueType == null || reader.ValueType == typeof(Byte?)) && reader.Value == null)
            {
                return default(Byte);
            }
            else
            {
                Byte.TryParse(reader.Value != null ? reader.Value.ToString() : "", out Byte value);
                return value;
            }
        }

        /// <summary>
        /// 写json
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="value"></param>
        /// <param name="serializer"></param>
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
                writer.WriteValue(default(Byte));
            else
                writer.WriteValue(value);
        }
    }

}
